import React, { cloneElement, PropsWithChildren, ReactElement, useState } from 'react';
import { Button, message, Popconfirm, Spin, Descriptions, Badge, Tag, Space, Modal } from 'antd';
import { useRequest } from 'ahooks';
import {
  ArticleNormalCategory,
  ArticleStatus,
} from "common/utils/data";
import {
  completeAllImgUrl,
  completeImgUrl,
  getRichTextArticleTitleCategoryPrefix,
  completeAllIframeUrl,
} from "common/utils/utils";
import { articleV1AdminControllerShow, articleV1AdminControllerUpdate } from "@/services/auto/articleAdmin";
import styles from './index.less';
import { VerticalAlignTopOutlined } from "@ant-design/icons";
import { blue } from "@ant-design/colors";
import Reject from "../Reject";
import 'braft-editor/dist/output.css';

interface Props {
  data: API.ArticleAdminIndexResult;
  reload?: () => void;
}

export default function Detail(props: PropsWithChildren<Props>){
  const { data, reload, children } = props;

  const [visible,setVisible] = useState<boolean>(false);

  const {
    data: detail,
    run,
    loading,
  } = useRequest(()=>articleV1AdminControllerShow({uuid: data.uuid}), {
    manual: true,
  });

  const {runAsync: patchRun} = useRequest(articleV1AdminControllerUpdate,{
    manual: true,
    onSuccess: (res, [_, req])=>{
      reload?.();
      if(req?.isStick === undefined){
        setVisible(false);
      }else{
        run();
      }
      message.success('操作成功');
    }
  })

  return (<>
      {cloneElement(children as ReactElement, {
        onClick: ()=>{
          setVisible(true);
          run();
        }
      })}
    <Modal
      title="详情"
      destroyOnClose
      onCancel={() => setVisible(false)}
      open={visible}
      width={1200}
      footer={
        <>
          {detail && (
            <div style={{ textAlign: 'right' }}>
              {detail.status === ArticleStatus.REVIEW && (
                <Space>
                  <Reject uuid={data.uuid} reload={()=>{
                    setVisible(false);
                    reload?.();
                  }} />
                  <Popconfirm
                    title="确认发布吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => {
                      patchRun({uuid: detail.uuid},{status: ArticleStatus.PUBLISH});
                    }}
                  >
                    <Button type="primary">发布</Button>
                  </Popconfirm>
                </Space>
              )}
              {detail.status === ArticleStatus.PUBLISH && (
                <Popconfirm
                  title="确认下架吗？"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun({uuid: detail.uuid},{status: ArticleStatus.REVIEW});
                  }}
                >
                  <Button danger type="primary">下架</Button>
                </Popconfirm>
              )}
            </div>
          )}
        </>
      }
    >
      <Spin spinning={loading}>
        {!detail && <div style={{ minHeight: '400px' }} />}
      </Spin>
      {detail && (
        <Descriptions bordered size="small" className={styles.descLabelWidth}>
          <Descriptions.Item label="标题" span={3}>
            <Badge
              count={
                <Popconfirm
                  title={detail.isStick ? '取消当前置顶吗？' : '确认当前置顶吗？'}
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => {
                    patchRun({uuid: detail.uuid},{ isStick: detail.isStick === 1 ? 0 : 1 });
                  }}
                >
                  <VerticalAlignTopOutlined
                    style={{
                      color: detail.isStick ? blue.primary : 'initial',
                      fontSize: '18px',
                      cursor: 'pointer',
                    }}
                    title={detail.isStick ? '置顶中' : '未置顶'}
                  />
                </Popconfirm>
              }
            >
              {detail.title}
            </Badge>
          </Descriptions.Item>
          <Descriptions.Item label="Tag" span={2}>
            {
              detail.categories.map(it=>{
                return getRichTextArticleTitleCategoryPrefix(it as ArticleNormalCategory)
              }).join('')
            }
          </Descriptions.Item>
          <Descriptions.Item label="关键词" span={1}>
            {detail.keywords.map((item, index) => <Tag key={index}>{item}</Tag>)}
          </Descriptions.Item>
          <Descriptions.Item label="作者用户" span={3}>
            {`${detail.user.name}（${detail.user.mobile}）`}
          </Descriptions.Item>
          <Descriptions.Item label="缩略图" span={3}>
            {detail.thumbnails?.length ? <a
              href={completeImgUrl(detail.thumbnails[0])}
              target="_blank"
              className="flex justify-center"
            >
              <img src={completeImgUrl(detail.thumbnails[0])} alt="图片" className="h-40"/>
            </a> : '--'}
          </Descriptions.Item>
          <Descriptions.Item label="描述" span={3}>
            {detail.desc}
          </Descriptions.Item>
          <Descriptions.Item label="正文内容" span={3}>
            <div
              className="braft-output-content"
              dangerouslySetInnerHTML={{
                __html: completeAllIframeUrl(completeAllImgUrl(detail.ext!.content)),
              }}
            />
          </Descriptions.Item>
        </Descriptions>
      )}
    </Modal>
    </>
  );
};
